package com.example.demo.thread;

/**
 * @Deacription 线程安全测试类
 * @Author xiatian
 * @Date 2020/7/30 7:30 下午
 **/

public class ThreadSafeDemo {

    public int safeState;

    public void notSafeAction() {
        int former = safeState++;
        int later = safeState;
        while (safeState < 100000) {

            if (former != later - 1) {
                System.out.println("出现线程不安全行为former = " + former + " later = " + later);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSafeDemo threadNotSafe = new ThreadSafeDemo();
        Thread threadA = new Thread() {
            @Override
            public void run() {
                threadNotSafe.notSafeAction();
            }
        };
        Thread threadB = new Thread() {
            @Override
            public void run() {
                threadNotSafe.notSafeAction();
            }
        };
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();



    }


}
